package com.zj.sqlSession;

import com.zj.exception.ZJBatisException;
import com.zj.executor.Executor;
import com.zj.transaction.ManagedTransactionFactory;
import com.zj.transaction.Transaction;
import com.zj.transaction.TransactionFactory;
import com.zj.transaction.TransactionIsolationLevel;
import com.zj.utils.Configuration;
import com.zj.utils.Environment;

import java.sql.SQLException;

public class DefaultSqlSessionFactory implements SqlSessionFactory {
    private final Configuration configuration;

    public DefaultSqlSessionFactory(Configuration configuration) {
        this.configuration = configuration;
    }
    @Override
    public SqlSession openSession() {
        return this.openSessionFromDataSource((TransactionIsolationLevel)null, false);
    }

    private SqlSession openSessionFromDataSource(TransactionIsolationLevel level, boolean autoCommit) {
        Transaction tx = null;
        DefaultSqlSession var8;
        try {
            Environment environment = this.configuration.getEnvironment();
            TransactionFactory transactionFactory = (TransactionFactory)(environment != null && environment.getTransactionFactory() != null ? environment.getTransactionFactory() : new ManagedTransactionFactory());
            tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
            Executor executor = this.configuration.newExecutor(tx);
            var8 = new DefaultSqlSession(this.configuration, executor, autoCommit);
        } catch (Exception var12) {
            this.closeTransaction(tx);
            throw new ZJBatisException("Error opening session.  Cause: " + var12);
        } finally {

        }
        return var8;
    }

    private void closeTransaction(Transaction tx) {
        if (tx != null) {
            try {
                tx.close();
            } catch (SQLException ignore) {
                // Intentionally ignore. Prefer previous error.
            }
        }
    }
}
